package com.wing.product.controller.admin;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.enterprisecab.feign.EnterpriseCabClient;
import com.wing.order.model.entity.CabInventoryProduct;
import com.wing.order.service.CabInventoryProductService;
import com.wing.platform.feign.PlatformClient;
import com.wing.product.model.entity.ProductDetail;
import com.wing.product.model.entity.ProductDetailAttribute;
import com.wing.product.model.entity.ProductDetailSpec;
import com.wing.product.service.ProductDetailAttributeService;
import com.wing.product.service.ProductDetailService;
import com.wing.product.service.ProductDetailSpecService;
import com.wing.web.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.apache.pulsar.shade.org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author xiayang
 */
@Validated
@Api(value = "Admin-产品明细表管理", tags = "#/product/productDetail")
@RestController("productDetailController")
@RequestMapping("product/admin/productDetail")
@RequiredArgsConstructor
public class ProductDetailController {

    private final ProductDetailService productDetailService;

    private final EnterpriseCabClient enterpriseCabClient;
    private final CabInventoryProductService cabInventoryProductService;
    private final PlatformClient platformClient;

    @Autowired
    ProductDetailAttributeService productDetailAttributeService;

    @Autowired
    ProductDetailSpecService productDetailSpecService;

    @ApiOperation(value = "查询所有产品明细表", notes = "搜索")
    @GetMapping("/list")
    public PageResult<ProductDetail> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            String skuCode,
            String skuName,
            String skuSpec,
            Long productTypeId,
            String codes,
            String pricingMethod,
            String planId,
            Long orderId) {
        Page<ProductDetail> pg = new Page<>(page, limit);
        Map<String,Object> paramMap = new HashMap();
        paramMap.put("sort", StrUtil.toUnderlineCase(sort));
        paramMap.put("order", StrUtil.toUnderlineCase(order));
        paramMap.put("skuCode", skuCode);
        paramMap.put("skuName", skuName);
        paramMap.put("skuSpec", skuSpec);
        paramMap.put("planId", planId);
        paramMap.put("productTypeId", productTypeId);
        paramMap.put("orderId", orderId);
        if (!StrUtil.isEmpty(pricingMethod)) {
            paramMap.put("pricingMethod", pricingMethod);
        }

        if (StrUtil.isNotBlank(codes)) {
            String[] split = codes.split(",");
            List<String> strings = Arrays.asList(split);
            paramMap.put("notInListIds", strings);
        }
        IPage<ProductDetail> list = productDetailService.pageList4app(pg, paramMap);
        list.getRecords().forEach(info -> {
            info.setRate(info.getTaxRate());
            info.setTaxPrice(info.getCurrentCostPrice());
        });
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "查询所有云仓产品", notes = "搜索")
    @GetMapping("/getPlatformProductDetailVOList")
    public PageResult<com.wing.platform.order.model.response.ProductDetailVO> getPlatformProductDetailVOList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            @RequestParam(defaultValue = "false") Boolean cloud,
            @RequestParam(name = "skuName", required = false) String skuName,
            @RequestParam(name = "skuCode", required = false) String skuCode,
            @RequestParam(name = "productCategoryId", required = false) String productCategoryId,
            @RequestParam(name = "skuSpecValueNames", required = false) String skuSpecValueNames) {
        PageResult<com.wing.platform.order.model.response.ProductDetailVO> list = platformClient.getPlatformProductDetailVOList(page, limit, sort, order, true, skuName, skuCode, productCategoryId, skuSpecValueNames);
        return new PageResult<>(list.getData(), list.getCount());
    }

    @ApiOperation(value = "查询渠道端产品", notes = "搜索")
    @GetMapping("/getChannelProductDetailList")
    public PageResult<com.wing.platform.order.model.response.ProductDetailVO> getChannelProductDetailList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "pd.create_time") String sort,
            @RequestParam(defaultValue = "desc") String order,
            @RequestParam(defaultValue = "false") Boolean cloud,
            @RequestParam(name = "skuName", required = false) String skuName,
            @RequestParam(name = "skuCode", required = false) String skuCode,
            @RequestParam(name = "enterpriseCode", required = false) String enterpriseCode) {
        PageResult<com.wing.platform.order.model.response.ProductDetailVO> list = platformClient.getChannelProductDetailList(page, limit, sort, order, skuName, skuCode, JwtUtils.getChannelCode());
        return new PageResult<>(list.getData(), list.getCount());
    }


    @ApiOperation(value = "添加产品明细表", notes = "添加")
    @PostMapping("/add")
    public JsonResult add(@RequestBody ProductDetail productDetail) {
        ProductDetail detail = productDetailService.getProductDetailBySkuCode(productDetail.getSkuCode());
        if (detail != null) {
            return JsonResult.fail("物料编码已存在!");
        }
        if (productDetailService.save(productDetail)) {
            //添加规格
            for (ProductDetailSpec detailSpec : productDetail.getProductDetailSpecList()) {
                detailSpec.setProductDetailId(productDetail.getId());
            }
            productDetailSpecService.saveBatch(productDetail.getProductDetailSpecList());
            //添加属性
            for (ProductDetailAttribute detailAttribute : productDetail.getProductDetailAttributeList()) {
                detailAttribute.setProductDetailId(productDetail.getId());
            }
            productDetailAttributeService.saveBatch(productDetail.getProductDetailAttributeList());
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "修改产品明细表", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@RequestBody ProductDetail productDetailParam) {
        ProductDetail productDetail = productDetailService.getById(productDetailParam.getId());
        if (productDetail == null) {
            return JsonResult.fail("修改失败！");
        }
        QueryWrapper<ProductDetail> productDetailQueryWrapper = new QueryWrapper<>();
        productDetailQueryWrapper.ne("id", productDetailParam.getId());
        productDetailQueryWrapper.eq("sku_code", productDetailParam.getSkuCode());
        List<ProductDetail> productDetailList = productDetailService.list(productDetailQueryWrapper);
        if (!productDetailList.isEmpty() && productDetailList.size() > 0) {
            return JsonResult.fail("输入的料号已重复，请重新输入！");
        }
        if (productDetailService.updateById(productDetailParam)) {
            //删除物料规格
            productDetailSpecService.remove(Wrappers.<ProductDetailSpec>query().lambda().eq(ProductDetailSpec::getProductDetailId, productDetailParam.getId()));
            //添加规格
            for (ProductDetailSpec detailSpec : productDetailParam.getProductDetailSpecList()) {
                detailSpec.setProductDetailId(productDetailParam.getId());
            }
            productDetailSpecService.saveBatch(productDetailParam.getProductDetailSpecList());
            //删除物料属性
            productDetailAttributeService.remove(Wrappers.<ProductDetailAttribute>query().lambda().eq(ProductDetailAttribute::getProductDetailId, productDetailParam.getId()));
            //添加属性
            for (ProductDetailAttribute detailAttribute : productDetailParam.getProductDetailAttributeList()) {
                detailAttribute.setProductDetailId(productDetailParam.getId());
            }
            productDetailAttributeService.saveBatch(productDetailParam.getProductDetailAttributeList());
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "删除产品明细表", notes = "删除")
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long productDetailId) {
        if (productDetailService.removeById(productDetailId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "查询所有产品明细(不分页)", notes = "查询所有产品明细(不分页)")
    @GetMapping("/getProductDetailByProductId")
    public JsonResult<ProductDetail> getProductDetailByProductId(Long productId) {
        QueryWrapper<ProductDetail> wrapper = new QueryWrapper<>();
        wrapper.eq("product_id", productId);
        List<ProductDetail> productDetailList = productDetailService.list(wrapper);
        return JsonResult.success(productDetailList);
    }

    @ApiOperation(value = "查询产品详情", notes = "搜索")
    @GetMapping("/getProductDetailBySkuCode")
    public JsonResult<ProductDetail> getProductDetailBySkuCode(String skuCode) {
        return JsonResult.success(productDetailService.getProductDetailBySkuCode(skuCode));
    }

    /**
     * 查询出库计划商品信息
     *
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/getProductDetailPageList")
    public PageResult<ProductDetail> getProductDetailPageList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            ProductDetail productDetail) {
        //搜索
        IPage<ProductDetail> list = productDetailService.getProductDetailPageList(productDetail, page, limit);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @ApiOperation(value = "查询所有产品", notes = "查询")
    @GetMapping("/getAll")
    public JsonResult<ProductDetail> getAll() {
        QueryWrapper<ProductDetail> wrapper = new QueryWrapper<>();
        wrapper.select("sku_code", "sku_name", "product_type_id");
        List<ProductDetail> productDetail = productDetailService.list(wrapper);
        return JsonResult.success(productDetail);
    }

    @ApiOperation(value = "初始化添加数据", notes = "查询")
    @GetMapping("/initAddData")
    public JsonResult<ProductDetail> initAddData() {
        List<ProductDetail> productDetailList = new ArrayList<>();
        for (int i = 1; i <= 100; i++) {
            ProductDetail productDetail = new ProductDetail();
            productDetail.setRemark(i + "");
            productDetailList.add(productDetail);
        }
        return JsonResult.success(productDetailList);
    }

    /**
     * @param id  产品库存id
     * @param num 采购数
     * @return
     */
    @GetMapping("/upById")
    public JsonResult upById(@RequestParam("id") Long id, @RequestParam("num") Integer num) {
        CabInventoryProduct inventoryProduct = cabInventoryProductService.getById(id);
        inventoryProduct.setQuantity(inventoryProduct.getQuantity() - num);
        if (cabInventoryProductService.updateById(inventoryProduct)) {
            return JsonResult.success("修改成功");
        }
        return JsonResult.fail();
    }

    @ApiOperation(value = "畅捷通-存货同步", notes = "畅捷通-存货同步")
    @GetMapping("/sync")
    public JsonResult sync() {
        try {
            productDetailService.chanjetInventorySync();
            return JsonResult.success("畅捷通-存货同步成功");
        } catch (BusinessException e) {
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "类别绑定-物料列表", notes = "类别绑定-物料列表")
    @GetMapping("/bindList")
    public PageResult<ProductDetail> bindList(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(name = "skuName", required = false) String skuName,
            @RequestParam(name = "skuCode", required = false) String skuCode,
            @RequestParam(name = "skuSpec", required = false) String skuSpec,
            @RequestParam(name = "productCategoryId", required = false) Long productCategoryId) {
        Page<ProductDetail> pg = new Page<>(page, limit);
        QueryWrapper<ProductDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.isNull("product_type_id");
        if(StringUtils.isNotBlank(skuName)){
            queryWrapper.like("sku_name", skuName);
        }
        if(StringUtils.isNotBlank(skuCode)){
            queryWrapper.like("sku_code", skuCode);
        }
        if(StringUtils.isNotBlank(skuSpec)){
            queryWrapper.like("sku_spec", skuSpec);
        }
        if(productCategoryId != null){
            queryWrapper.eq("product_category_id", productCategoryId);
        }
        IPage<ProductDetail> list = productDetailService.getBaseMapper().selectPage(pg, queryWrapper);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }


    @ApiOperation(value = "物料类别绑定", notes = "物料类别绑定")
    @PostMapping("/bind")
    public JsonResult bind(
            @RequestParam("productTypeId") Long productTypeId,
            @RequestParam("productDetailIds") String productDetailIds) {
        List<String> productDetailIdList = new ArrayList<>(Arrays.asList(productDetailIds.split(",")));

        productDetailService.productDetailBind(productTypeId, productDetailIdList);
        return JsonResult.success("类别-物料绑定成功");
    }

}
